<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends BaseController
{
    public $model = Category::class;


    public function index(Request $request) {

        $input = $request->input();
        $users = Category::with('child')->where('parent_id', 0)->orderBy("id", "desc")
            ->paginate(\request('per_page', 999));
        return $this->paginate($users);
    }


    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $this->validate($request, [
            'title' => 'required',
            'parent_id' => 'filled|integer',
            'id' => 'filled|exists:categories'
        ]);
        $input = $request->input();
        $id = \request("id");
        $parent_id = $input['parent_id'] ?? 0;

        $exist_id = Category::where('title', \request('title'))
            ->where('parent_id', $parent_id)->value('id');
        if ($id) {
            if ($exist_id && ($id != $exist_id)) {
                return $this->failed("已经存在");
            }
            $model = Category::find($id);
//            if ($model->is_edit == 0)
//                return $this->failed('不可编辑');
            $model->update($input);
        } else {
            if ($exist_id)
                return $this->failed("已经存在");

            $info = Category::create($input);
            $id = $info->id;
        }
        return $this->success($id);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $cate = Category::find ($id);
            if ($cate->is_edit == 0)
                continue;
            if ($cate->parent_id == 0) {
                Category::where('parent_id', $cate->id)->delete();
            }
            $cate->delete();
        }
        return $this->success([]);
    }


}

